package com.songlanyun.modules.usercart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.enums.GoodsConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.common.utils.StrUtil;
import com.songlanyun.modules.account.entity.AccountEntity;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.exception.GoodsExceptionEnum;
import com.songlanyun.modules.exception.OrderException;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.modules.goods.entity.GoodsAuthShop;
import com.songlanyun.modules.goods.entity.GoodsSku;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.goods.service.GoodsSkuService;
import com.songlanyun.modules.shop.entity.ShopEntity;
import com.songlanyun.modules.shop.service.ShopService;
import com.songlanyun.modules.singlegoods.entity.ProductSingleGoodsEntity;
import com.songlanyun.modules.singlegoods.service.ProductSingleGoodsService;
import com.songlanyun.modules.usercart.model.dto.UserCartDTO;
import com.songlanyun.modules.usercart.model.vo.UserCartGroupVo;
import com.songlanyun.modules.usercart.model.vo.UserCartVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.modules.usercart.dao.UserCartDao;
import com.songlanyun.modules.usercart.entity.UserCart;
import com.songlanyun.modules.usercart.service.UserCartService;
import org.springframework.transaction.annotation.Transactional;


@Service("userCartService")
public class UserCartServiceImpl extends ServiceImpl<UserCartDao, UserCart> implements UserCartService {

    @Autowired
    private ShopService shopService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private GoodsSkuService goodsSkuService;

    @Autowired
    private ProductSingleGoodsService productSingleGoodsService;

    @Override
    public UserCart create(UserCart entity) {
        this.baseMapper.insert(entity);
        return entity;
    }

    @Override
    public UserCart modify(UserCart entity) {
        this.baseMapper.updateById(entity);
        return entity;
    }

    @Override
    public void remove(Long id) {
        this.removeById(id);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserCart> page = this.page(
                new Query<UserCart>().getPage(params),
                new QueryWrapper<UserCart>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询我的购物车
     * @param shopId
     * @param userId
     * @return
     */
    @Override
    public List<UserCartGroupVo> myCarts(Long shopId,Long userId) {

        List<UserCartVo> list = this.baseMapper.myCarts(userId);

        final Map<Long, List<UserCartVo>> collect = list.stream().collect(Collectors.groupingBy(UserCartVo::getSourceShopId));


        List<UserCartGroupVo> result = collect.entrySet().stream().map(o -> {
            UserCartGroupVo userCartGroupVo = new UserCartGroupVo();
            userCartGroupVo.setSourceShopId(o.getKey());
            userCartGroupVo.setSourceShopName(o.getValue().get(0).getSourceShopName());
            userCartGroupVo.setProxy(false);
            userCartGroupVo.setUserCartList(o.getValue());
            return userCartGroupVo;
        }).collect(Collectors.toList());


        if(shopId>0)
        {
            /**
             * 如果有店铺把当前的店铺放在第一个
             */
            List<UserCartGroupVo> newResult = new ArrayList<>();
            Optional<UserCartGroupVo> first = result.stream().filter(o -> o.getSourceShopId().equals(shopId)).findFirst();
            if(first.isPresent())
            {
                newResult.add(first.get());
                List<UserCartGroupVo> others = result.stream().filter(o -> !o.getSourceShopId().equals(shopId)).collect(Collectors.toList());
                newResult.addAll(others);
                result = newResult;
            }
        }

        List<UserCartGroupVo> realResult = new ArrayList<>();

        result.forEach(vo->{
            Map<Long, List<UserCartVo>> col = vo.getUserCartList().stream().collect(Collectors.groupingBy(UserCartVo::getShopId));

            col.entrySet().stream().forEach(map->{
                UserCartGroupVo userCartGroupVo = new UserCartGroupVo();
                userCartGroupVo.setShopId(map.getKey());
                userCartGroupVo.setSourceShopId(vo.getSourceShopId());
                userCartGroupVo.setSourceShopName(vo.getSourceShopName());
                userCartGroupVo.setProxy(!map.getKey().equals(vo.getSourceShopId()));
                userCartGroupVo.setUserCartList(map.getValue());
                realResult.add(userCartGroupVo);
            });

        });
        return realResult;
    }

    /**
     * 添加商品到购物车
     * @param userId
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public UserCart add(Long userId, UserCartDTO dto) {

        /**
         * 来源门店
         */
        ShopEntity shop = shopService.loadShopBy(dto.getSourceShopId(),true);
        AccountEntity user = accountService.getUserById(userId,true);
        Goods goods = goodsService.getById(dto.getGoodsId());
        //商品没有审核通过不能加入购物车
        if(!GoodsConstant.VerifyStatus.YES.equals(goods.getVerifyStatus()))
        {
            throw new RRException(GoodsExceptionEnum.GOODS_VERIFY_NOT);
        }

        if(goods.getPointGoods())
        {
            throw new RRException(GoodsExceptionEnum.POINT_EXCHANGE_GOODS_NOT_CART);
        }
        GoodsAuthShop goodsAuthShop = goods.loadAuthByShop(dto.getSourceShopId());
        if(goodsAuthShop==null)
        {
            throw new RRException(GoodsExceptionEnum.NOT_PROXY_AUTH);
        }


        //商品未上架不能加入购物车
        if(!goodsAuthShop.isAdded())
        {
            throw new RRException(GoodsExceptionEnum.GOODS_NOT_ADDED);
        }
        //获取商品的sku
        GoodsSku goodsSku = goodsSkuService.loadByGoodsAndSkuHashCode(goods.getId(), dto.getSkuHashCode());
        if(goodsSku==null)
        {
            //商品的sku不存在
            throw new RRException(GoodsExceptionEnum.GOODS_SKU_NOT_EXISTS);
        }
        //获取商品sku中的单品
        ProductSingleGoodsEntity singleGoods = goodsSku.loadSingleGoods();
        if(singleGoods==null)
        {
            //单品不存在
            throw new RRException(GoodsExceptionEnum.SINGLE_GOODS_NOT_EXISTS);
        }

        if(goods.getLimitBuyNum()>0)
        {
            int num = this.getCartGoodsCount(userId,dto.getGoodsId());
                num = num + dto.getAddNum();
                if(num>goods.getLimitBuyNum())
                {
                throw new RRException(String.format(GoodsExceptionEnum.GOODS_LIMIT_ERROR.getMsg(),goods.getLimitBuyNum()),GoodsExceptionEnum.GOODS_LIMIT_ERROR.getCode());
            }
        }


        UserCart old = this.getByUserAndGoodsAndSkuCode(userId,dto.getSourceShopId(),dto.getGoodsId(),dto.getSkuHashCode());
        if(old!=null)
        {
            //不能超过商品的库存
            if(singleGoods.getAbleStock() <  old.getNum() + dto.getAddNum())
            {
                throw new RRException(String.format(GoodsExceptionEnum.SINGLE_GOODS_STOCK_SAFE.getMsg(), StrUtil.truncation(singleGoods.getTitle(),10)),GoodsExceptionEnum.SINGLE_GOODS_STOCK_SAFE.getCode());
            }

            //如果购物车中存在已经加入的商品和商品sku,做更新
            old.setSalePrice(goodsSku.getSalePrice());
            old.setPoint(goodsSku.getExchangePoint());
            old.setSkuSetName(goodsSku.getSkuSetName());
            old.setNum( old.getNum() + dto.getAddNum());
            old.setShopName(goods.loadShop().getShopName());
            old.setSourceShopName(shop.getShopName());
            old.setGoodsShortTitle(goods.getShortTitle());
            old.setGoodsTitle(goods.getTitle());
            old.setGoodsCover(StringUtils.isBlank(goodsSku.getCover())?goods.getCover():goodsSku.getCover());
            this.modify(old);
            return old;
        }
        else
        {

            //不能超过商品的库存
            if(singleGoods.getAbleStock() <  dto.getAddNum())
            {
                throw new RRException(String.format(GoodsExceptionEnum.SINGLE_GOODS_STOCK_SAFE.getMsg(), StrUtil.truncation(singleGoods.getTitle(),10)),GoodsExceptionEnum.SINGLE_GOODS_STOCK_SAFE.getCode());
            }
            //如果购物车中不存在加入的商品和商品sku,做新增
            UserCart cart = new UserCart();
            cart.setNum(dto.getAddNum());
            cart.setGoodsId(dto.getGoodsId());
            cart.setCreateTime(new Date());
            cart.setGoodsCover(StringUtils.isBlank(goodsSku.getCover())?goods.getCover():goodsSku.getCover());
            cart.setGoodsTitle(goods.getTitle());
            cart.setGoodsShortTitle(goods.getShortTitle());
            cart.setSkuHashCode(dto.getSkuHashCode());

            cart.setSourceShopId(shop.getId());
            cart.setSourceShopName(shop.getShopName());
            cart.setPlatformStore(goods.getPlatformStore());

            cart.setShopId(goods.getShopId());
            cart.setShopName(goods.loadShop().getShopName());

            cart.setUserId(user.getId());
            cart.setSkuSetName(goodsSku.getSkuSetName());
            cart.setSkuHashCode(goodsSku.getSkuHashCode());
            cart.setSalePrice(goodsSku.getSalePrice());
            cart.setPoint(goodsSku.getExchangePoint());
            cart.setThird(goods.getThird());
            this.create(cart);
            return cart;
        }
    }

    @Override
    public int getCartGoodsCount(Long userId, Long goodsId) {
        return this.baseMapper.getCartGoodsCount(userId,goodsId);
    }

    /**
     * 设置商品购物车的数量
     * @param shopId
     * @param userId
     * @param userCartDTO
     * @return
     */
    @Override
    @Transactional
    public UserCart setNum(Long shopId, Long userId, UserCartDTO userCartDTO) {

        AccountEntity user = accountService.getUserById(userId,true);
        UserCart cart = this.baseMapper.selectById(userCartDTO.getId());

        //如果购物车商品不存在或不是自己的购物车商品,报错
        if(cart==null || !cart.getUserId().equals(user.getId()))
        {
            throw new RRException(OrderException.USER_CART_EXISTS);
        }

        Goods goods = goodsService.getByShopIdAndId(shopId,cart.getGoodsId());
        //商品没有审核通过不能加入购物车
        if(!GoodsConstant.VerifyStatus.YES.equals(goods.getVerifyStatus()))
        {
            throw new RRException(GoodsExceptionEnum.GOODS_VERIFY_NOT);
        }

        GoodsAuthShop publishAuth = goods.loadPublishAuth();
        //商品未上架不能加入购物车
        if(publishAuth == null || !publishAuth.isAdded())
        {
            throw new RRException(GoodsExceptionEnum.GOODS_NOT_ADDED);
        }


        //获取商品的sku
        GoodsSku goodsSku = goodsSkuService.loadByGoodsAndSkuHashCode(goods.getId(), cart.getSkuHashCode());
        if(goodsSku==null)
        {
            //商品的sku不存在
            throw new RRException(GoodsExceptionEnum.GOODS_SKU_NOT_EXISTS);
        }

        //获取商品sku中的单品
        ProductSingleGoodsEntity singleGoods = goodsSku.loadSingleGoods();
        if(singleGoods==null)
        {
            //单品不存在
            throw new RRException(GoodsExceptionEnum.SINGLE_GOODS_NOT_EXISTS);
        }

        //商品限购,加入的商品数不参大于商品限购数量
        if(goods.getLimitBuyNum()>0 && userCartDTO.getAddNum()>goods.getLimitBuyNum())
        {
            throw new RRException(String.format(GoodsExceptionEnum.GOODS_LIMIT_ERROR.getMsg(),goods.getLimitBuyNum()),GoodsExceptionEnum.GOODS_LIMIT_ERROR.getCode());
        }

        if(singleGoods.getAbleStock() < userCartDTO.getAddNum())
        {
            throw new RRException(String.format(GoodsExceptionEnum.SINGLE_GOODS_STOCK_SAFE.getMsg(), StrUtil.truncation(singleGoods.getTitle(),10)),GoodsExceptionEnum.SINGLE_GOODS_STOCK_SAFE.getCode());
        }

        //如果购物车中存在已经加入的商品和商品sku,做更新
        cart.setSalePrice(goodsSku.getSalePrice());
        cart.setSkuSetName(goodsSku.getSkuSetName());
        cart.setNum(userCartDTO.getAddNum());
        cart.setShopName(cart.getShopName());
        cart.setGoodsShortTitle(goods.getShortTitle());
        cart.setGoodsTitle(goods.getTitle());
        this.modify(cart);
        return cart;
    }

    /**
     * 查询当前用户商品的sku在购物车中的对象
     * @param userId
     * @param goodsId
     * @param skuHashCode
     * @return
     */
    private UserCart getByUserAndGoodsAndSkuCode(Long userId,Long sourceShopId,Long goodsId,String skuHashCode)
    {
        UserCart first = this.getOne(new LambdaQueryWrapper<UserCart>()
                .eq(UserCart::getUserId,userId)
                .eq(UserCart::getGoodsId,goodsId)
                .eq(UserCart::getSourceShopId,sourceShopId)
                .eq(UserCart::getSkuHashCode,skuHashCode)
                .last("limit 1")
        );
        return first;
    }








}
